package com.sophossystems.client.asmon.dao.spring;

import java.sql.SQLException;
import java.util.List;

import com.sophossystems.client.asmon.dao.StatusDao;
import com.sophossystems.client.asmon.dto.StatusDTO;
import com.sophossystems.client.asmon.exceptions.DaoException;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.HibernateCallback;

public class StatusDaoImpl extends AbstractDAO implements StatusDao {
	
	private static Logger logger = Logger.getLogger(StatusDaoImpl.class);

	@Override
	public StatusDTO findByPrimaryKey(final int idStatus) throws DaoException {
		StatusDTO status = null;
		try {
			status = (StatusDTO) getHibernateTemplate().execute(
					new HibernateCallback() {
						
						@Override
						public Object doInHibernate(Session session) throws HibernateException,
								SQLException {
							final Query oQuery = session.createQuery("SELECT s.idStatus as idStatus, " +
									"s.descripcion as descripcion FROM " 
									+ getTableName() + " s WHERE s.idStatus = :id");
							oQuery.setInteger("id", idStatus);
							StatusDTO statusDto = (StatusDTO) 
									oQuery.setResultTransformer(
									Transformers.aliasToBean(
											StatusDTO.class)).list().get(0);
							return statusDto;
							
						}
					});
		} catch (Exception e) {
			logger.error("Error: getStatus, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getStatus, cause: "
					+ e.getMessage());
		}
		return status;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<StatusDTO> findAll() throws DaoException {
		List<StatusDTO> status = null;
		try {
			status = (List<StatusDTO>) getHibernateTemplate().execute(
					new HibernateCallback() {
						
						@Override
						public Object doInHibernate(Session session) throws HibernateException,
								SQLException {
							final Query oQuery = session.createQuery("SELECT s.idStatus as idStatus, " +
									"s.descripcion as descripcion FROM " 
									+ getTableName() + " s ORDER BY s.idStatus");
							List<StatusDTO> statusDto = oQuery.setResultTransformer(
									Transformers.aliasToBean(StatusDTO.class)).list();
							return statusDto;
						}
					});
		} catch (Exception e) {
			logger.error("Error: getStatus, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getStatus, cause: "
					+ e.getMessage());
		}
		return status;
	}

	public String getTableName() {
		return "Status";
	}
}
